﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/10/24 9:35:26
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary;
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;

namespace BusinessLibrary
{
    /// <summary>
    /// 扫码枪类
    /// </summary>
    public class Scan : IPlugin
    {
        /// <summary>
        /// 其他错误信息
        /// </summary>
        public List<string> OtherErrorCodes { get; set; } = new List<string>() {
            "NOREAD"
        };
        /// <summary>
        /// 错误barcode
        /// </summary>
        public readonly string ERROR_BARCODE = "ERROR";
        /// <summary>
        /// 描述信息
        /// </summary>
        public string Description => "条码相关业务处理";
        /// <summary>
        /// 执行方法
        /// </summary>
        /// <param name="pluginParam"></param>
        /// <returns></returns>
        public string Excute(PluginParamEntity pluginParam)
        {
            string result = string.Empty;
            if (pluginParam != null
                && APPInstance.PLC != null
                && APPInstance.PLC.IsConnected)
            {
                string identity = pluginParam.Identity.ToUpper();
                switch (identity)
                {
                    case "SCAN_BARCODE": result = ScanBarcode(pluginParam); break;
                    case "SCAN_MES": result = ScanMES(pluginParam); break;
                    case "SCAN_PLC": result = ScanPLC(pluginParam); break;
                }
            }
            return result;
        }
        /// <summary>
        /// 返回一个窗口
        /// </summary>
        /// <param name="pluginParam"></param>
        /// <returns></returns>

        public HWFrmWithTitle GetForm(PluginParamEntity pluginParam)
        {
            return null;
        }
        /// <summary>
        /// 返回一个 Bitmap
        /// </summary>
        /// <returns></returns>
        public Bitmap GetBitmap()
        {
            return null;
        }
        /// <summary>
        /// SCAN_BARCODE 1-OK,2-NG,3-NG(长度）,4-NG(前缀)
        /// </summary>
        /// <param name="pluginParam"></param>
        /// <returns></returns>
        private string ScanBarcode(PluginParamEntity pluginParam)
        {
            string methodName = "条码判定";
            this.Info($"【{pluginParam.Tag}】开始 - {methodName}");
            var businessConfig = BusinessConfig.Instance();
            var scanEntity = CommonHelper.GetJson(pluginParam.ParamString, new ScanExcuteEntity()
            {
                ScanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            });
            try
            {
                if (!string.IsNullOrWhiteSpace(scanEntity.Barcode) && scanEntity.Barcode.EndsWith("\r\n"))
                {
                    scanEntity.Barcode = scanEntity.Barcode.Substring(0, scanEntity.Barcode.Length - "\r\n".Length);
                }
                scanEntity.Barcode = string.IsNullOrWhiteSpace(scanEntity.Barcode)
                    || (this.OtherErrorCodes.Find(v => v.ToLower().Equals(scanEntity.Barcode.ToLower())) != null)
                    ? ERROR_BARCODE : scanEntity.Barcode;
                this.Info($"【{pluginParam.Tag}】{methodName}，条码：{scanEntity.Barcode}");
                if (string.IsNullOrWhiteSpace(scanEntity.Barcode) || scanEntity.Barcode.ToUpper().Equals("ERROR"))
                {
                    scanEntity.ScanResult = 2;
                }
                else
                {
                    if (businessConfig.IsCheckBarcodeLength && scanEntity.Barcode.Length != businessConfig.BarcodeLength)
                    {
                        scanEntity.ScanResult = 3;
                    }
                    else if (businessConfig.IsCheckBarcodePrev
                        && !string.IsNullOrWhiteSpace(businessConfig.BarcodePrev)
                        && !scanEntity.Barcode.StartsWith(businessConfig.BarcodePrev))
                    {
                        scanEntity.ScanResult = 4;
                    }
                    else
                    {
                        scanEntity.ScanResult = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
            string result = CommonHelper.GetJsonString(scanEntity, Newtonsoft.Json.Formatting.None);
            this.Info($"【{pluginParam.Tag}】结束 - {methodName}，返回结果：{result}");
            return result;
        }
        /// <summary>
        /// SCAN_MES
        /// </summary>
        /// <param name="pluginParam"></param>
        /// <returns></returns>
        private string ScanMES(PluginParamEntity pluginParam)
        {
            string methodName = "扫码MES判定";
            this.Info($"【{pluginParam.Tag}】开始 - {methodName}");
            //1-OK,2-NG
            string result = "1";
            try
            {
                var scanEntity = CommonHelper.GetJson(pluginParam.ParamString, new ScanExcuteEntity()
                {
                    ScanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
                var mesResult = (string.IsNullOrWhiteSpace(scanEntity.Barcode) || scanEntity.Barcode.ToUpper().Equals(MultiScanHelper.ERROR_BARCODE)) ?
                    new MESResult()
                    {
                        Code = "200",
                        Success = true,
                        Message = "条码无效，无需上传"
                    } :
                    !MesCommonHelper.IsMESOffline ?
                    MesBusiness.InCheck(scanEntity.Barcode, scanEntity.ScanTime, scanEntity.ScanResult) :
                    new MESResult()
                    {
                        Code = "200",
                        Success = true,
                        Message = "MES离线"
                    };
                result = mesResult.IsSuccessReturn ? "1" : "2";
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
            this.Info($"【{pluginParam.Tag}】结束 - {methodName}，返回结果：{result}");
            return result;
        }
        /// <summary>
        /// SCAN_PLC
        /// </summary>
        /// <param name="pluginParam"></param>
        /// <returns></returns>
        private string ScanPLC(PluginParamEntity pluginParam)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            int writerType = 1;
            string methodName = "扫码结果写入PLC";
            this.Info($"【{pluginParam.Tag}】开始 - {methodName}");
            try
            {
                if (APPInstance.PLC != null
                    && APPInstance.PLC.IsConnected
                    && !string.IsNullOrWhiteSpace(pluginParam.ParamString))
                {
                    var scan = CommonHelper.GetJson(pluginParam.ParamString, new ScanExcuteEntity()
                    {
                        Barcode = "ERROR",
                        MESResult = 0,
                        ScanResult = 0,
                        ScanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    });
                    //不把MES结果归纳到扫码结果
                    scan.MESResult = (short)ENGCode.OK;//scan.MESResult == 1 ? (short)ENGCode.OK : (short)ENGCode.NG_SCAN;//scan.MESResult;
                    scan.ScanResult = scan.ScanResult == 1 && scan.MESResult == (short)ENGCode.OK ? (short)ENGCode.OK : (short)ENGCode.NG_SCAN;// scan.ScanResult;
                    this.Info($"【{pluginParam.Tag}】{methodName} - 写PLC, 结果：{CommonHelper.GetJsonString(scan, Newtonsoft.Json.Formatting.None)}");


                    if (!string.IsNullOrWhiteSpace(pluginParam.Tag))
                    {
                        var temp = pluginParam.Tag.Replace("扫码枪#", "");
                        int tempValue = 1;
                        if (!string.IsNullOrWhiteSpace(temp) && int.TryParse(temp, out tempValue))
                        {
                            writerType = tempValue;
                        }
                    }
                    writerType = writerType <= 1 || writerType >= 6 ? 1 : writerType;


                    var emptyValue = new string('\0', 32);
                    APPInstance.PLC.Write(scan.PlcEntity.BarcodeAddress, emptyValue, true, writerType);
                    APPInstance.PLC.Write(scan.PlcEntity.BarcodeAddress, scan.Barcode, true, writerType);
                    APPInstance.PLC.Write(scan.PlcEntity.ScanTimeAddress, emptyValue, true, writerType);
                    APPInstance.PLC.Write(scan.PlcEntity.ScanTimeAddress, scan.ScanTime, true, writerType);
                    APPInstance.PLC.Write(scan.PlcEntity.ScanMESAddress, scan.MESResult, true, writerType);
                    APPInstance.PLC.Write(scan.PlcEntity.ScanResultAddress, scan.ScanResult, true, writerType);
                    APPInstance.PLC.Write(scan.PlcEntity.ResultDoneAddress, (short)1, true, writerType);
                }
            }
            catch (Exception ex)
            {
                this.Error(ex);
            }
            finally
            {
                stopwatch.Stop();
                this.Info($"【{pluginParam.Tag}】【统计】{methodName}，Writer：{writerType}，耗时：{stopwatch.ElapsedMilliseconds} 毫秒");
            }
            this.Info($"【{pluginParam.Tag}】结束 - {methodName}");
            return string.Empty;
        }
    }
}
